package com.leyou.service;

import com.leyou.common.utils.JsonUtils;
import com.leyou.entity.UserInfo;
import com.leyou.interceptor.UserInterceptor;
import com.leyou.pojo.Cart;
import net.minidev.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate template;

    private final  String KEY_PERFIX = "CART";
    public void addCart(Cart cart) {
        //用户
        UserInfo user = UserInterceptor.getUser();
        String key = KEY_PERFIX + user.getId();
        String cartKey = cart.getSkuId().toString();
        //判断是否存在
        BoundHashOperations<String, Object, Object> bound = template.boundHashOps(key);
        if(bound.hasKey(cartKey)){
            //是，修改
            String  json = bound.get(cartKey).toString();
            Cart parse = JsonUtils.parse(json, Cart.class);
            parse.setNum(parse.getNum()+ cart.getNum());
            //写回redis
            bound.put(cartKey,JsonUtils.serialize(parse));
        }else{
            //否，新增
            bound.put(cartKey,JsonUtils.serialize(cart));
        }

    }

    public List<Cart> query() {
        String key = "CART28";
        BoundHashOperations<String, Object, Object> bound = template.boundHashOps(key);
        List<Cart> collect = bound.values().stream().map(r -> JsonUtils.parse(r.toString(), Cart.class)).collect(Collectors.toList());
        for (Cart cart : collect) {
            System.out.println(cart.getOwnSpec());
        }
        return collect;

    }
}
